package com.itljm.cxrMarket.filter;

import com.itljm.cxrMarket.entity.LoginUser;
import com.itljm.cxrMarket.utils.JwtUtil;
import com.itljm.cxrMarket.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;
import java.util.Objects;

/**
 * @author ljm
 * @date 2024/11/1 17:09
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 获取访问令牌
        String token = request.getHeader("AccessToken");
        if (!StringUtils.hasText(token)) {
            // 没有则放行
            filterChain.doFilter(request, response);
            return;
        }
        String userId;
        try {
            Claims claims = jwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            throw new BadCredentialsException("token非法，请重新登陆");
        }
        String key = "user:" + userId;
        LoginUser loginUser = redisUtil.getCacheObject(key);
        // 判断用户信息是否存在
        if (Objects.nonNull(loginUser)){
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "拒绝访问: 用户未登录");
            return;
        }
        filterChain.doFilter(request, response);
    }
}
